/*
Copyright (C) 2013 Carlo de Falco

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 3 of the License, or
  (at your option) any later version.
  
  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.
  
  You should have received a copy of the GNU General Public License
  along with Octave; see the file COPYING.  If not, see
  <http://www.gnu.org/licenses/>.  

Author: Carlo de Falco <carlo@guglielmo.local>
Created: 2013-03-08

*/

#ifndef OCTAVE_FILE_IO_UTILS_H
# define OCTAVE_FILE_IO_UTILS_H

#include <fstream>
#include <octave/oct.h>
#include <octave/ov.h>
#include <octave/zfstream.h>
#include <octave/octave.h>
#include <octave/parse.h>
#include <octave/toplev.h>
#include <octave/load-save.h>
#include <octave/ls-oct-binary.h>
#include <octave/oct-map.h>
#include <cstring>

static bool check_gzip_magic (const std::string& fname);
static bool fexists (const std::string& fname);
static load_save_format format = LS_BINARY;
static oct_mach_info::float_format flt_fmt = oct_mach_info::flt_fmt_unknown;
static bool swap = false;

class octave_file_io_intf
{

public:

  octave_file_io_intf () 
    : filename ("") {};
  
  int fopen (const char *fname, std::ios::openmode m);
  int gzfopen (const char *fname, std::ios::openmode m);
  
  int fclose (void);
  int gzfclose (void);

  int do_read (const std::string &);
  int do_write (const std::string &);

  double* get_data (void) { return buffer.fortran_vec (); };
  int get_data_rank (void) { return buffer.ndims (); };
  int get_data_size (void) { return buffer.numel (); };

  void get_data_shape (int*); 
  void set_data_shape (const int, const int*);

  void clear_data (void) { buffer.clear (); };

 private:

  int read (const std::string &);
  int gzread (const std::string &);

  int write (const std::string &);
  int gzwrite (const std::string &);

  std::fstream file;
  gzifstream gzifile;
  gzofstream gzofile;
  std::string filename;
  int current_mode;
  Array<double> buffer;

};

#endif
